using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using ShopForWeb.UI.Extensions;

namespace ShopForWeb.UI.Filters;
public class RedisCacheFilter : Attribute, IActionFilter
{
  private IDistributedCache _cache;
  public RedisCacheFilter(IDistributedCache cache)
  {
    _cache = cache;
  }

  public void OnActionExecuted(ActionExecutedContext context)
  {
    if (context.HttpContext.Response.Headers.ContainsKey("CacheData"))//判断请求头有没有关于缓存的标记
      return;                                                        //有数据就退出
    string key = this.GetKey(context.HttpContext.Request);
    Controller? controller = context.Controller as Controller;
    if (controller != null)
    {
      var data = controller.ViewBag.Data;
      _cache.SetInstance<dynamic>(key, data as object);
    }
  }

  public void OnActionExecuting(ActionExecutingContext context)
  {
    string key = this.GetKey(context.HttpContext.Request);
    var data = _cache.GetInstance<dynamic>(key);//动态类型
    if (data != null)
    {
      context.HttpContext.Response.Headers.Add("CacheData", "Redis");//说明数据来源
      Controller? controller = context.Controller as Controller;
      if (controller != null)
      {
        controller.ViewBag.Data = data;
        context.Result = controller.View();
      }

    }
  }
  private string GetKey(HttpRequest request)
  {
    var keyContent = request.Path.Value + request.QueryString.Value;
    if (request.Method.ToUpper() != "DELETE" && request.Method.ToUpper() != "GET" && request.Form.Count > 0)
    {
      foreach (var item in request.Form)
      {
        keyContent += $"{item.Key}={item.Value.ToString()}";
      }
    }
    return keyContent;
  }
}
